<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>类的装饰</title>
</head>
<body>
    <h1>类的装饰</h1>

    <script>
        // 装饰器函数
        function testable(target) {
            target.isTestable = true;
        }

        // 使用装饰器
        @testable
        class MyTestableClass {
            // ...
        }

        // 带参数的装饰器
        function log(name) {
            return function(target) {
                target.logName = name;
            };
        }

        @log('MyClass')
        class Example {
            // ...
        }

        // 实际应用示例
        // 1. 添加版本信息
        function version(v) {
            return function(target) {
                target.version = v;
            };
        }

        @version('1.0.0')
        class API {
            getData() {
                return 'some data';
            }
        }

        // 2. 注入依赖
        function injectable(target) {
            target.inject = function(dependencies) {
                return new target(...dependencies);
            };
        }

        @injectable
        class UserService {
            constructor(httpClient, logger) {
                this.httpClient = httpClient;
                this.logger = logger;
            }
        }

        // 3. 添加元数据
        function controller(path) {
            return function(target) {
                target.prototype.path = path;
                if (!target.prototype.routes) {
                    target.prototype.routes = new Map();
                }
            };
        }

        @controller('/api')
        class UserController {
            @route('GET', '/users')
            getUsers() {
                // ...
            }

            @route('POST', '/users')
            createUser() {
                // ...
            }
        }

        // 4. 性能监控
        function measure(target) {
            const methods = Object.getOwnPropertyNames(target.prototype);
            
            methods.forEach(method => {
                if (method !== 'constructor') {
                    const original = target.prototype[method];
                    
                    target.prototype[method] = function(...args) {
                        const start = performance.now();
                        const result = original.apply(this, args);
                        const end = performance.now();
                        
                        console.log(`${method} 执行时间: ${end - start}ms`);
                        return result;
                    };
                }
            });
        }

        @measure
        class Calculator {
            add(a, b) {
                return a + b;
            }

            multiply(a, b) {
                return a * b;
            }
        }
    </script>
</body>
</html> 